#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <protocol_define.h>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QFile>

class TcpServer : public QObject
{
    Q_OBJECT
public:
    explicit TcpServer(QObject *parent = nullptr);
public slots:
    void init();

    void startListen(QString ip , QString port);

    void sendData(const QString & data);

    void sendFile(const QString & filepath,int seek = 0 );


signals:
    void signReadyRead(TcpProtocol);

    void signConnected();

    void signDisconnected();

    void signDisplayError(QAbstractSocket::SocketError);
public slots:
    void newClientConnect();

    void readMessage();

    void disConnect();

    void updateServerProgress();

    void acceptConnection();

    void displayError(QAbstractSocket::SocketError socketError);
private slots:
    void updateClientProgress(qint64 numBytes);
private:
    void save2File(TcpProtocol);

    void sendReadFileData(TcpProtocol);

    void sendfile(const QString & filepath,int seek = 0 );
private:
    QTcpServer* m_server;
    QTcpSocket* m_socket;
    QFile       m_file;
    QByteArray  m_buffer;
    QString     m_filePath;
    QTcpServer* m_tcpServer;
    QTcpSocket* m_filesocket;
    qint64      m_totalBytes;
    qint64      m_bytesReceived;
    qint64      m_fileNameSize;
    QString     m_fileName;
    QFile *     m_localFile;
    QByteArray  m_inBlock;
    QFile *     m_sendlocalFile;
    qint64      m_sendtotalBytes;
    qint64      m_sendbytesWritten;
    qint64      m_sendbytesToWrite;
    qint64      m_sendpayloadSize;
    QString     m_sendfileName;
    QByteArray  m_sendoutBlock;

    void startTransfer();
};

#endif // TCPSERVER_H
